package fun.boomcat.luckyhe.mirai.plugin.luckymoney.util;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Lucky_He
 * @date 2021年9月5日 14:15
 * @description ConfigUtil
 */
public class ConfigUtil {
    private static File configPath;
    private static String configFileName = "config.properties";
    private static Properties properties = null;

    public static void initConfigPath(File path, String configContent) throws IOException {
        configPath = path;

        File[] files = configPath.listFiles();
        boolean hasConfig = false;
        for (File file : files) {
            if (file.getName().equals(configFileName)) {
                hasConfig = true;
                break;
            }
        }
        if (!hasConfig) {
            copyConfigPathFromResource(configContent);
        }
    }

    private static void copyConfigPathFromResource(String configContent) throws IOException {
        FileOutputStream fos = new FileOutputStream(configPath.getPath() + "/" + configFileName);

        byte[] buf = configContent.getBytes(StandardCharsets.UTF_8);
        fos.write(buf);
        fos.close();
    }

    private static Properties getProperties() throws IOException {
        if (properties == null) {
            InputStream is = new BufferedInputStream(new FileInputStream(configPath.getPath() + "/" + configFileName));
            properties = new Properties();
            properties.load(new InputStreamReader(is, StandardCharsets.UTF_8));
            is.close();
        }

        return properties;
    }

    public static Map<String, String> getMySqlConnInfo() throws IOException {
        Properties p = getProperties();
        Map<String, String> resMap = new HashMap<>();
        resMap.put("url", p.getProperty("mysql.url"));
        resMap.put("username", p.getProperty("mysql.username"));
        resMap.put("password", p.getProperty("mysql.password"));

        return resMap;
    }

    public static String getMoneyUnit() throws IOException {
        Properties p = getProperties();
        return p.getProperty("money.unit");
    }
}
